import React, { useEffect, useState  , Key} from 'react'
import { Button, Form, Input, Table, Card , Tooltip, message} from 'antd';
import { SearchOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons"
import { useNavigate } from 'react-router-dom';
import style from './index.module.css'

import { getHosSetListRequest , deleteHospitalSetRequest , deleteAllHospitalSetRequest} from '@api/hospital/hospitalSet'       //引入Api

import type {
  getHosSetListRecordsType,   //数组的类型
  getHosSetListItemsType,     //数组的每一项的类型
} from '@api/hospital/model/hospitalSetTypes' 
import type { searchHosParamsType } from './types';  //引入查询医院函数的参数类型


export default function HospitalSet() {
  //使用编程式路由导航
  const usenavigate = useNavigate()

  const [hospitalList, setHospitalList] = useState<getHosSetListRecordsType>([]) //数据初始值
  const [total, setTotal] = useState(0) //数据总条数
  const [current, setCurrent] = useState(1) //当前页码
  const [pageSize, setPageSize] = useState(10) //每页条数  
  const [loading, setLoading] = useState(false) //页面是否加载
  const [fieldValue , setFieldValue] = useState<searchHosParamsType>({})//查询时发送的数据
  //定义一个控制页面重新渲染的stata
  const [deleteHos , setDeltteHos] = useState(true)
  //定义状态控制批量删除按钮的禁用
  const [deleteall , setDeleteall] = useState(true)
  //定义状态保存选择医院的id
  const [ids , setIds] = useState<Key[]>([])



  //刚加载组件的时候就请求数据渲染页面
  useEffect(() => {
    //在请求开始之前设置isLoading为true
    setLoading(true);

    //封装一个请求函数才可以,记得后续调用
    const getHosSetList = async () => {
      const result = await getHosSetListRequest({
        page: current,
        limit: pageSize,
        ...fieldValue
      })
      //请求回数据设置到页面         
      setHospitalList(result.records)
      //总数据条数
      setTotal(result.total)

      //在请求开始之后设置isLoading为false
      setLoading(false);
    }
    getHosSetList();
  }, [current, pageSize , fieldValue , deleteHos])


  const columns = [
    {
      title: '序号',
      align: "center" as "center",  //文本居中 
      dataIndex: 'index',  //dataIndex可以代替key
      width: 60,           //列的宽度
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
      align: "center" as "center",  //文本居中 
    },
    {
      title: '医院编号',
      dataIndex: 'hoscode',
      align: "center" as "center",  //文本居中 
    },
    {
      title: 'api基础路径',
      dataIndex: 'apiUrl',
      align: "center" as "center",  //文本居中 
    },
    {
      title: '签名',
      dataIndex: 'signKey',
      align: "center" as "center",  //文本居中 
    },
    {
      title: '联系人姓名',
      dataIndex: 'contactsName',
      align: "center" as "center",  //文本居中 
    },
    {
      title: '联系人手机',
      dataIndex: 'contactsPhone',
      align: "center" as "center",  //文本居中 
    },
    {
      title: '操作',
      dataIndex: "do",
      align: "center" as "center",  //文本居中 
      width: 120,                  //列的宽度
      fixed: "right" as "right",    //固定最右边一列
      render(_:any , data:getHosSetListItemsType) {
        const {id} = data //第二个参数是当前这一行的数据 可以解构出这条数据专有的id
        
        return (
          <div>
            {/* 修改按钮的逻辑 */}
            <Tooltip title={"修改医院"}>
              <Button 
                type='primary' 
                icon={<EditOutlined />} 
                className={style.mr}
                onClick = {() => usenavigate(`/syt/hospatil/updateHospital/${id}`) }
              ></Button>
            </Tooltip>

            {/* 删除按钮的逻辑 */}
            <Tooltip title={"删除医院"}>
              <Button 
                type='primary' 
                danger 
                icon={<DeleteOutlined />}
                onClick = {deleteHospitalHandle(id)}
              ></Button>
            </Tooltip>
          </div >
        )
      }
    }
  ];


  //1.页码和每页条数改变的函数   参数就是当前页码和pageSize
  const pageChangeHandle = (current: number, pageSize: number) => {
    //点击改变页码和每页条数之后改变State发送请求渲染
    setCurrent(current)
    setPageSize(pageSize)
  }


  //2.点击查询的回调函数
  const searchHospitalHandle = (fieldValue:searchHosParamsType) => {
    //点击查询改变State 发送请求
    setFieldValue(fieldValue)
  }

  //3.点击清空的回调函数
  const clearFieldValueHandle = () => {
    //设置查询状态中的数据为空查询渲染
    setFieldValue({})
  }



  //4.点击添加医院的回调函数
  const addHosHandle = () => {
    //点击添加去医院页面
    usenavigate("/syt/hospatil/addHospital")
  }


  //5.点击删除的回调函数
  const deleteHospitalHandle =  (id:number) => {
    return async () => {
      //删除医院
      await deleteHospitalSetRequest(id)

      //提示
      message.success("删除成功!")

      //页面重新渲染
      setDeltteHos(!deleteHos)

    }
  }


  //7，点击批量删除的逻辑
  const deleteAllHandle = async() => {
    //发送批量删除请求
    await deleteAllHospitalSetRequest(ids)

    //提示
    message.success("删除成功!")

    //页面重新渲染
    setDeltteHos(!deleteHos)

    //批量删除之后把按钮禁用
    setDeleteall(true)

  }


  return (
    <div className={style.outer}>
      <Card>

        <Form
          name="basic"
          wrapperCol={{ span: 30 }}
          layout='inline'
          onFinish={searchHospitalHandle}
        >
          <Form.Item name="hosname">
            <Input placeholder="医院名称" />
          </Form.Item>

          <Form.Item name="hoscode">
            <Input placeholder='医院编号' />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
            <Button type="default" htmlType="reset" onClick = {clearFieldValueHandle}>
              清空
            </Button>
          </Form.Item>

        </Form>

        <div className={style.mt}>
          <Button type='primary' className={style.mr} onClick = {addHosHandle}>添加</Button>
          <Button type="primary" danger disabled = {deleteall} onClick = {deleteAllHandle} >批量删除</Button>
        </div>

        <Table
          columns={columns}        //列
          dataSource={hospitalList}  //每列数据
          className={style.mt}     //上边距
          scroll={{ x: 1300 }}     //横向滚动条长度
          bordered                 //边框
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          //页面加载中的动画
          loading={loading}

          //显示选择框
          rowSelection = {{
            onChange(ids:Key[]){  //多选框改变触发
              //只要选择了就让批量删除按钮接触禁用 没选择就禁用
              ids.length > 0 ? setDeleteall(false) : setDeleteall(true)

              //把选择地医院的id保存到状态中 等下发送批量删除请求要用
              setIds(ids)
              
            }
          }}

          //分页器
          pagination={{
            //页码的配置：当前页码
            current,
            //总数据的数量
            total,
            //每页条数
            pageSize,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [2, 3, 4, 5],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            //数据的总条数
            showTotal(total) {
              return `数据的总条数是${total}`
            },

            //页码和每页条数改变的函数
            onChange: pageChangeHandle


          }}
        />
      </Card>
    </div>
  )
}
